package com.pudding.aiservicedemo;

import com.pudding.tools.ModelUtil;
import dev.langchain4j.agent.tool.Tool;
import dev.langchain4j.agent.tool.ToolSpecification;
import dev.langchain4j.agent.tool.ToolSpecifications;
import dev.langchain4j.memory.ChatMemory;
import dev.langchain4j.memory.chat.MessageWindowChatMemory;
import dev.langchain4j.model.chat.ChatLanguageModel;
import dev.langchain4j.model.openai.OpenAiChatModel;
import dev.langchain4j.service.AiServices;
import dev.langchain4j.service.MemoryId;
import dev.langchain4j.service.UserMessage;

import java.time.LocalDateTime;

public class UserAiService {

    interface Assistant {
        String chat(@MemoryId Long userId, @UserMessage String message);
    }

    @Tool("获取当前⽇期")
    public static String dateUtil() {
        return LocalDateTime.now().toString();
    }

    public static void main(String[] args) throws NoSuchMethodException {
        //构建模型，过程略
        ChatLanguageModel model = OpenAiChatModel.builder()
                .apiKey(ModelUtil.API_KEY_OPENAI)
                .build();

        ChatMemory chatMemory = MessageWindowChatMemory.withMaxMessages(10);
        ToolSpecification toolSpecification = ToolSpecifications.toolSpecificationFrom(UserAiService.class.getMethod("dateUtil"));

        Assistant assistant = AiServices.builder(Assistant.class)
                .chatLanguageModel(model)
//                .chatMemory(chatMemory)  //添加ChatMemory
                .chatMemoryProvider(memoryId -> MessageWindowChatMemory.withMaxMessages(10))
                .tools(toolSpecification) //添加Tools⼯具
                .build();

        //与⽤户1的交互
        System.out.println(">>>" + assistant.chat(1L, "你好，我是楼兰"));
        System.out.println(">>>" + assistant.chat(1L, "我的名字是什么"));
        //与⽤户2的交互
        System.out.println(">>>" + assistant.chat(2L, "你好，我是⽼王"));
        System.out.println(">>>" + assistant.chat(2L, "我的名字是什么"));
    }
}
